package com.ctshk.sapp.finance.controller;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ctshk.common.annotations.OperationLogAnnotation;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.OperationLogModel;
import com.ctshk.common.enums.OperationLogType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.rpc.finance.dto.stamptax.StampTaxRefundListDTO;
import com.ctshk.rpc.finance.excel.ExcelData;
import com.ctshk.rpc.finance.excel.ExcelTemp;
import com.ctshk.rpc.finance.excel.ExportExcelUtils;
import com.ctshk.rpc.finance.req.stamptax.StampTaxExportOutReq;
import com.ctshk.rpc.finance.req.stamptax.StampTaxRefundListReq;
import com.ctshk.rpc.finance.service.IFinanceStampTaxRefundService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import com.ctshk.common.web.support.BaseController;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 印花税退款记录 前端控制器
 * </p>
 *
 * @author 叶冠峰
 * @since 2021-04-05
 */
@RestController
@Api(value = "印花税退款", tags = "印花税退款")
@RequestMapping("/finance-stamp-tax-refund")
public class FinanceStampTaxRefundController extends BaseController {

    @DubboReference
    private IFinanceStampTaxRefundService stampTaxRefundService;


    @ApiOperation(value = "列表", notes = "列表（叶冠峰）")
    @OperationLogAnnotation(operModul = OperationLogModel.FINANCE, operType = OperationLogType.QUERY, operTitle = "印花税退款-列表", operDesc = "印花税退款-列表")
    @PostMapping("/list")
    public Result<PageResponse<StampTaxRefundListDTO>> list(@RequestBody StampTaxRefundListReq req) {
        req.setUserId(getCurrentUser(getRequest()).getId());
        return stampTaxRefundService.list(req);
    }

    @ApiOperation(value = "導出未退款申請表", notes = "導出未退款申請表（叶冠峰）")
    @OperationLogAnnotation(operModul = OperationLogModel.FINANCE, operType = OperationLogType.QUERY, operTitle = "印花税退款-導出未退款申請表", operDesc = "印花税退款-導出未退款申請表")
    @PostMapping("/export-out")
    public void exportOut(@RequestBody @Valid StampTaxExportOutReq req) {
        ExcelData data = stampTaxRefundService.exportOut(req);
        if (data == null){
            throw new BusinessException(SystemError.FINANCE_BILL_17023);
        }
        try {
            ExportExcelUtils.exportExcel(getResponse(),"未退款印花税.xlsx",data);
        }catch (Exception e){
            throw new BusinessException(SystemError.SYS_437);
        }
    }

    @ApiOperation(value = "导入TIC退款结果", notes = "导入TIC退款结果（叶冠峰）")
    @OperationLogAnnotation(operModul = OperationLogModel.FINANCE, operType = OperationLogType.UPDATE, operTitle = "印花税退款-导入TIC退款结果", operDesc = "印花税退款-导入TIC退款结果")
    @PostMapping("/export-in")
    public Result exportIn(@RequestPart("file") MultipartFile file) {
        if (file.isEmpty()){
            throw new BusinessException(SystemError.SYS_409,"file");
        }
        List<ExcelTemp> temp = new ArrayList<>();
        Workbook wb0 = null;
        InputStream inputStream = null;
        try {
            //文件后缀名
            String fileExtension = getFileExtension(file.getOriginalFilename());
            inputStream = file.getInputStream();
            //根据指定的文件输入流导入Excel从而产生Workbook对象
            if ("xls".equals(fileExtension)){
                wb0 = new HSSFWorkbook(inputStream);
            }else if ("xlsx".equals(fileExtension)){
                wb0 = new XSSFWorkbook(inputStream);
            }
            if (wb0 != null){
                //获取Excel文档中的第一个表单
                Sheet sht0 = wb0.getSheetAt(0);
                //对Sheet中的每一行进行迭代
                for (Row r : sht0) {
                    //如果当前行的行号（从0开始）未达到2（第三行）则从新循环
                    if (r.getRowNum() < 1) {
                        continue;
                    }
                    //设置单元格类型
                    Cell cell3 = r.getCell(3);
                    cell3.setCellType(CellType.STRING);
                    Cell cell4 = r.getCell(4);
                    cell4.setCellType(CellType.STRING);
                    Cell cell6 = r.getCell(6);
                    cell6.setCellType(CellType.STRING);
                    //创建实体类
                    ExcelTemp refund = new ExcelTemp();
                    //封装实体类属性
                    refund.setReceiptNumber(cell3.getStringCellValue());
                    refund.setTaxAmount(new BigDecimal(cell4.getStringCellValue()));
                    refund.setProductNumber(cell6.getStringCellValue());
                    System.out.println("封装后的数据 =====>>> " + refund.toString());
                    temp.add(refund);
                }
            }
            return stampTaxRefundService.exportIn(temp,getCurrentUser(getRequest()).getId());
        }catch (Exception e){
            throw new BusinessException(SystemError.SYS_437);
        }finally {
            try {
                inputStream.close();
            }catch (Exception e){
                throw new BusinessException(SystemError.SYS_437);
            }
        }
    }


    /**
     * 获取文件扩展名(后缀)
     * @param filename
     * @return
     */
    public String getFileExtension(String filename) {
        if (StringUtils.isNotBlank(filename)) {
            String string = filename.trim();
            int index = filename.lastIndexOf(".");
            if (index > 0 && index < string.length() - 1) {
                return string.substring(index + 1);
            }
        }
        return null;
    }

}
